﻿using System;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI.WebControls;
using System.Xml.Linq;
using Newtonsoft.Json;
using SocialWidgetsContrib.Widgets.Shared;
using Telerik.Sitefinity.Web.UI;
using Telerik.Sitefinity.News.Model;
using Telerik.Web.UI;
using Telerik.Sitefinity.Web.UI.ControlDesign;
using Telerik.Sitefinity.Localization;
using Telerik.Sitefinity;
using Telerik.Sitefinity.Modules.Pages.Web.UI;
using Telerik.Sitefinity.Web.DataResolving;
using Telerik.Sitefinity.Modules.News.Web.UI;
using Telerik.Sitefinity.Pages.Model;
using Telerik.Sitefinity.GenericContent.Model;


namespace SocialWidgetsContrib.Widgets.YouTube
{
    public class YouTubeVideRotatorWidget : SimpleView
    {
        const string FEED_URL = "http://gdata.youtube.com/feeds/base/users/{0}/uploads?alt=rss";
        const int BUTTON_WIDTH = 24;

        public string UserName { get; set; }
        public int MaximumVideos { get; set; }
        public bool AutoRotate { get; set; }
        public int RotationTimerSeconds { get; set; }
        public int RotatorWidth { get; set; }
        public int RotatorHeight { get; set; }
        public bool ShowNavigationButtons { get; set; }

        protected override void OnLoad(System.EventArgs e)
        {
            // ensure the username is valid
            if (string.IsNullOrEmpty(UserName)) return;

            var sb = new StringBuilder();

            try
            {
                // retrieve contents
                var url = string.Format(FEED_URL, UserName);
                var vidXml = XDocument.Load(url);
                if (vidXml == null) return;

                // parse to collection
                var videos = from t in vidXml.Descendants("item") select new { href = t.Element("link").Value, alt = t.Element("title").Value, src = ToThumbnail(t.Element("link").Value) };

                var imageRotator = new ImageRotatorUtility("YouTube");
                string jsonVideos = JsonConvert.SerializeObject(videos);
                string script = imageRotator.GenerateScript(jsonVideos, AutoRotate, RotationTimerSeconds * 1000, ShowNavigationButtons, RotatorWidth, RotatorHeight);

                // HACK: http://www.sitefinity.com/devnet/forums/sitefinity-4-x/general-discussions/jquery-plugins-and-or-authoring-custom-jquery-functions-not-supported.aspx
                // Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "socialRotator", script);
                sb.Append(script);

                var first = videos.First();
                string html = imageRotator.GenerateHtml(RotatorWidth, RotatorHeight, first.href, first.src, first.alt);
                sb.Append(html);
            }
            catch
            {
                sb.Append("Flickr Image Query failed.");
            }


            YouTubeVideoRotator.Text = sb.ToString();
        }

        /// <summary>
        /// Retrieves a thumbnail for a youtube video link
        /// </summary>
        /// <param name="input">The url to the video.</param>
        /// <returns></returns>
        protected string ToThumbnail(string input)
        {
            // retrieve url
            var uri = new Uri(input);

            // parse to querystring
            var qs = HttpUtility.ParseQueryString(uri.Query);
            var vidID = qs["v"];

            // create thumbnail from qs
            return string.IsNullOrEmpty(vidID) ? string.Empty : string.Format("http://img.youtube.com/vi/{0}/0.jpg", vidID);
        }

        protected override void InitializeControls(GenericContainer container)
        {
            throw new NotImplementedException();
        }

        protected override string LayoutTemplateName
        {
            get { return "SocialWidgetsContrib.Resources.Views.YouTubeVideoRotatorWidget.ascx"; }
        }

        protected virtual Literal YouTubeVideoRotator
        {
            get
            {
                return Container.GetControl<Literal>("YouTubeVideoRotatorHtml", true);
            }
        }
    }
}
